from django.shortcuts import render, HttpResponse
from . import models
from django.core import validators
from django import forms
from utils.tencent.sms import send_sms_single
import random
from django.conf import settings
from sts.sts import Sts
from django.http import JsonResponse


class LoginModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label="手机号",
                                   validators=[validators.RegexValidator(r'1[3456789]\d{9}$', message="手机号码格式错误")])
    password = forms.CharField(label="密码", widget=forms.PasswordInput, )
    confirm_password = forms.CharField(label='重复密码', widget=forms.PasswordInput, )
    code = forms.CharField(label="验证码")

    # def clean_mobile_phone(self):
    #     tel = self.cleaned_data.get('mobile_phone')
    #     exits = models.UserInfo.objects.filter(mobile_phone=tel).exists()
    #     if exits:
    #         raise forms.ValidationError('手机号已经存在')
    #     return tel

    def clean(self):
        cleaned_data = super().clean()
        pwd1 = cleaned_data.get('password')
        pwd2 = cleaned_data.get('confirm_password')
        if pwd1 != pwd2:
            raise forms.ValidationError('密码不一致')
        return cleaned_data

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    # 初始化方法
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 每个字段的字段名和字段值
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入{}'.format(field.label)


def app01_login(request):
    if request.method == "GET":
        form = LoginModelForm()
        return render(request, 'app01_login.html', {'form': form})

    else:
        form = LoginModelForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.password = form.cleaned_data.get('password')
            user.save()
            print(form.cleaned_data)
            return HttpResponse('ok')
        else:
            print(form.errors)
            return render(request, 'app01_login.html', {'form': form})


def send_sms(request):
    """发送短信"""

    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse('模板不存在')
    code = random.randrange(1000, 9999)
    print(code)
    res = send_sms_single('151342', 856818, [code, ])
    print(res)
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])


def sts_demo(request):
    return render(request, 'sts_demo.html')


def cos_credential(request):
    config = {
        # 临时密钥有效时长，单位是秒
        'duration_seconds': 1800,
        'secret_id': settings.TENCENT_COS_ID,
        # 固定密钥
        'secret_key': settings.TENCENT_COS_KEY,

        # 换成你的 bucket
        'bucket': 'miaojiaxi-1304867879',
        # 换成 bucket 所在地区
        'region': 'ap-guangzhou',

        'allow_prefix': '*',

        'allow_actions': [
            # 上传方式
            'name/cos:PutObject',
            'name/cos:PostObject',
            # 'name/cos:InitiateMultipartUpload',
            # 'name/cos:ListMultipartUploads',
            # 'name/cos:ListParts',
            # 'name/cos:UploadPart',
            # 'name/cos:CompleteMultipartUpload'
        ],

    }
    sts = Sts(config)
    response = sts.get_credential()

    return JsonResponse(response)


def select_ceshi(request):
    return render(request, 'select_ceshi.html')
